from loguru import logger
import os
import sys
from datetime import datetime
from src.yamlLoader import YamlLoader

class Log:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self, log_dir="logs", log_level="INFO", rotation="10 MB", retention="30 days"):
        if self._initialized:
            return
        self._initialized = True
        """
        初始化日志配置
        :param log_dir: 日志存储目录
        :param log_level: 日志级别（DEBUG, INFO, WARNING, ERROR, CRITICAL）
        :param rotation: 日志文件分割条件（例如 "10 MB" 或 "1 day"）
        :param retention: 日志文件保留时间（例如 "30 days"）
        """
        self.log_dir = log_dir
        self.log_level = log_level
        self.rotation = rotation
        self.retention = retention

        # 创建日志目录
        os.makedirs(self.log_dir, exist_ok=True)

        # 配置日志
        self._configure_logger()

    def _configure_logger(self):
        """配置 loguru 日志器"""
        # 移除默认的日志处理器
        logger.remove()

        # 添加控制台日志处理器
        logger.add(
            sys.stdout,
            level=self.log_level,
            format=self._get_log_format(),
            colorize=True  # 启用颜色显示
        )

        # 添加文件日志处理器
        log_file = os.path.join(self.log_dir, f"{datetime.now().strftime('%Y-%m-%d')}.log")
        logger.add(
            log_file,
            level=self.log_level,
            format=self._get_log_format(),
            rotation=self.rotation,
            retention=self.retention,
            encoding="utf-8"
        )

    def _get_log_format(self):
        """获取日志格式"""
        return (
            "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
        )

    def debug(self, message):
        """记录 DEBUG 级别日志"""
        logger.debug(message)

    def info(self, message):
        """记录 INFO 级别日志"""
        logger.info(message)

    def warning(self, message):
        """记录 WARNING 级别日志"""
        logger.warning(message)

    def error(self, message):
        """记录 ERROR 级别日志"""
        logger.error(message)

    def critical(self, message):
        """记录 CRITICAL 级别日志"""
        logger.critical(message)

    def catch(self, func):
        """捕获函数异常并记录"""
        return logger.catch(func)
    
    
yaml_loader = YamlLoader()
config = yaml_loader.get_config()
# 初始化日志模块
log = Log(log_dir=config['log']['dir'], log_level=config['log']['level'],
                  rotation=config['log']['rotation'], retention=config['log']['retention'])
